from flask import Blueprint, jsonify
from flask_jwt_extended import jwt_required
import requests
from bs4 import BeautifulSoup
from http_status import HttpStatus
import utils

hot_search_bp = Blueprint('hot_search', __name__)

# 抓取百度热搜数据
def get_baidu_hot_search():
    url = 'https://top.baidu.com/board?tab=realtime'
    headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'
    }
    r = requests.get(url, headers=headers, timeout=30)
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text,'html.parser')
    title_list=soup.find_all(attrs={'class':'c-single-text-ellipsis'})
    hot_list=soup.find_all(attrs={'class':'hot-index_1Bl1a'})
    link_list=soup.find_all(attrs={'class':'title_dIF3B'})
    # 获取A标签的href值： <a class="title_dIF3B" href="https://***">***</a>
    link_list=[link.get('href') for link in link_list]
    return [{'title':title.text,'hot':hot.text, 'link': link} for title,hot,link in zip(title_list,hot_list,link_list)]

# 获取百度热搜的路由
@hot_search_bp.route('/baidu_hot_search', methods=['GET'])
@jwt_required()
def baidu_hot_search():
    # 获取热搜数据
    hot_search_data = get_baidu_hot_search()
    # 取得前30条数据
    hot_search_data = hot_search_data[:30]
    return utils.response(True, data=hot_search_data, message='获取成功', status=HttpStatus.CODE_SUECCESS)

def get_weather():
    # 查看天气-北京
    url = "https://www.weather.com.cn/weather1d/101010100.shtml"
    headers = {
    'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36'
    }
    r = requests.get(url, headers=headers, timeout=30)
    r.encoding = r.apparent_encoding
    soup = BeautifulSoup(r.text,'html.parser')
    tempNum=soup.find(attrs={'class':'tem'})
    weather = soup.find(attrs={'class':'wea'})
    print(tempNum)
    print(weather)
    return {'tempNum':tempNum.text, 'weather': weather.text}
# 查询当前时间和天气信息
@hot_search_bp.route('/header_info', methods=['GET'])
@jwt_required()
def header_info():
    now = utils.time_now()
    weatherInfo = get_weather()
    return utils.response(True, data={
        'now': now.strftime('%Y-%m-%d %H:%M:%S'), 
        'weather': weatherInfo['weather'] + " " +weatherInfo['tempNum'],
        }, message='获取成功', status=HttpStatus.CODE_SUECCESS)